package com.github.caijh.mall.exception;

import javax.inject.Inject;

import com.github.caijh.framework.core.exception.BizException;
import com.github.caijh.framework.core.model.R;
import com.github.caijh.mall.common.MessageConstants;
import org.springframework.context.MessageSource;
import org.springframework.context.i18n.LocaleContextHolder;
import org.springframework.http.HttpStatus;
import org.springframework.web.HttpMediaTypeNotSupportedException;
import org.springframework.web.bind.MissingServletRequestParameterException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestControllerAdvice;

@RestControllerAdvice
public class GlobalExceptionHandler {

    @Inject
    private MessageSource messageSource;

    @ResponseStatus(HttpStatus.OK)
    @ExceptionHandler(HttpMediaTypeNotSupportedException.class)
    public R<Void> bindException(HttpMediaTypeNotSupportedException e) {
        return new R<Void>().setCode(String.valueOf(HttpStatus.BAD_REQUEST.value()))
                            .setMessage(messageSource.getMessage(MessageConstants.HTTP_400, new Object[]{}, LocaleContextHolder.getLocale()));
    }

    @ExceptionHandler(Exception.class)
    @ResponseBody
    public R<Void> defaultExceptionHandler(Exception e) {
        String code = null;
        Object[] params = new Object[]{};
        if (e instanceof MissingServletRequestParameterException) {
            code = MessageConstants.HTTP_400;
        }
        if (e instanceof BizException) {
            code = ((BizException) e).getCode();
            params = ((BizException) e).getParams();
        }
        R<Void> result = new R<>();
        if (code != null) {
            String message = messageSource.getMessage(code, params, LocaleContextHolder.getLocale());
            result.setMessage(message);

        } else {
            result.setMessage(e.getLocalizedMessage());
        }

        return result;
    }

}
